﻿# -- Math_m.py
"""
    Copyright 2013 J. Kent Harbaugh

    This file is part of Raddel.

    Raddel is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Raddel is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Raddel.  If not, see <http://www.gnu.org/licenses/>.
"""



class Interp_t:
    def Interp(Self,Xnow):
        if Xnow<Self._XyPairs[0][0]:
            return Self._ExtrapVals[0]
        for idx in range(1,len(Self._XyPairs)):
            if Xnow<=Self._XyPairs[idx][0]:
                return (Self._XyPairs[idx-1][1]+Self._Coefs[idx]*
                    (Xnow-Self._XyPairs[idx-1][0]))
        return Self._ExtrapVals[1]
    def __call__(Self,Xnow):
        return Self.Interp(Xnow)
    def __init__(Self,XyPairs,ExtrapVals=None):
        for idx in range(1,len(XyPairs)):
            if XyPairs[idx][0]<=XyPairs[idx-1][0]:
                raise ValueError('Interp_t.__init__: not strictly ' 
                    'monatonic')
        Self._XyPairs=XyPairs
        if ExtrapVals==None:
            Self._ExtrapVals=(Self._XyPairs[0][1],Self._XyPairs[-1][1])
        else:
            Self._ExtrapVals=ExtrapVals
        Self._Coefs=[0]*len(Self._XyPairs)
        for idx in range(1,len(Self._XyPairs)):
            Self._Coefs[idx]=((Self._XyPairs[idx][1]-Self._XyPairs[idx-1][1])/
                (Self._XyPairs[idx][0]-Self._XyPairs[idx-1][0]))



class Table_t:
    def Lookup(Self,Xnow):
        for idx in range(len(Self._XyPairs)):
            if Xnow<=Self._XyPairs[idx][0]:
                return Self._XyPairs[idx][1]
        return Self._ExtrapVal
    def __call__(Self,Xnow):
        return Self.Lookup(Xnow)
    def __init__(Self,XyPairs,ExtrapVal=None):
        for idx in range(1,len(XyPairs)):
            if XyPairs[idx][0]<=XyPairs[idx-1][0]:
                raise ValueError('Table_t.__init__: not strictly ' 
                    'monatonic')
        Self._XyPairs=XyPairs
        if ExtrapVal==None:
            Self._ExtrapVal=Self._XyPairs[-1][1]
        else:
            Self._ExtrapVal=ExtrapVal



# -- Math_m.py
